package client;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import protocol.Packet;
import protocol.PacketCodeC;
import protocol.request.LoginRequestPacket;
import protocol.response.LoginResponsePacket;
import protocol.response.MessageResponse;
import util.LoginUtil;

import java.util.Date;
import java.util.UUID;

public class ClientHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("客户端开始登录...");

        LoginRequestPacket request = new LoginRequestPacket();
        request.setUserId(UUID.randomUUID().toString());
        request.setUsername("zxy");
        request.setPassword("123");

        ctx.channel().writeAndFlush(PacketCodeC.INSTANCE.encode(ctx.alloc(),request));
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf buf = (ByteBuf) msg;
        Packet packet = PacketCodeC.INSTANCE.decode(buf);
        if (packet instanceof LoginResponsePacket) {
            LoginResponsePacket loginResponsePacket = (LoginResponsePacket) packet;
            if (loginResponsePacket.isSuccess()) {
                System.out.println(new Date() + ":客户端登录成功");
                LoginUtil.markAsLogin(ctx.channel());
            } else {
                System.out.println(new Date() + ":客户端登录失败,原因是:" + loginResponsePacket.getReason());
            }
        } else if (packet instanceof MessageResponse) {
            MessageResponse messageResponse = (MessageResponse) packet;
            System.out.println("接收到服务端响应:【" + messageResponse.getMessage() + "】");
        }
    }


}
